# -*- coding: utf-8 -*-
import cv2
import time
import threading
import sys
import tty
import termios

from GStreamerWrapper import GStreamerWrapper

class WideAngleCamera:
    """
    广角相机类，封装了 GStreamerWrapper，用于设置分辨率和获取图像帧。
    """
    def __init__(self, width: int = 1920, height: int = 1080):
        """
        初始化广角相机。

        Args:
            width (int): 图像宽度，默认为 1920。
            height (int): 图像高度，默认为 1080。
        """
        self.frame_width = width
        self.frame_height = height
        self.wrapper = None
        self._is_running = False
        print(f"Initializing WideAngleCamera with resolution: {self.frame_width}x{self.frame_height}...")
        try:
            # 实例化 GStreamerWrapper
            self.wrapper = GStreamerWrapper(width=self.frame_width, height=self.frame_height)
            self._is_running = True
            print("GStreamerWrapper initialized successfully.")
        except Exception as e:
            print(f"Error initializing GStreamerWrapper: {e}")
            self.wrapper = None
            self._is_running = False

    def get_frame(self):
        """
        从相机获取一帧图像。

        Returns:
            numpy.ndarray: 图像帧（BGR格式），如果相机未运行或获取失败则返回 None。
        """
        try:
            if not self._is_running or self.wrapper is None:
                print("Camera is not running or GStreamerWrapper not initialized.")
                return None
            
            frame = self.wrapper.GetFrame()
            if frame is None:
                # print("Warning: Failed to get frame from camera.")
                pass # 频繁打印警告会刷屏，可以根据需要启用
            return frame
        except Exception as e:
            print(f"Error initializing GStreamerWrapper: {e}")
            self.stop()


    def stop(self):
        """
        停止相机数据流并释放资源。
        """
        if self._is_running and self.wrapper is not None:
            print("Stopping WideAngleCamera and releasing resources...")
            self.wrapper.StopThread()
            self._is_running = False
            print("WideAngleCamera stopped.")
        else:
            print("WideAngleCamera is already stopped or not initialized.")


